package logic

import (
	"context"
	"net/http"
	"path/filepath"
	"short-video-dev/pkg"
	"short-video-dev/videorpc/videorpc"

	"short-video-dev/api/internal/svc"
	"short-video-dev/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type VideoAddLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewVideoAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *VideoAddLogic {
	return &VideoAddLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *VideoAddLogic) VideoAdd(req *types.VideoAddRequest, r *http.Request) (resp *types.Response, err error) {
	// todo: add your logic here and delete this line

	video, m, err := r.FormFile("videoLink")
	if err != nil {
		return &types.Response{
			Message: "文件不存在",
			Code:    500,
			Data:    nil,
		}, nil
	}
	if m.Size > 200*1024*1024 {
		return &types.Response{
			Message: "视频文件过大，最大支持200MB",
			Code:    500,
			Data:    nil,
		}, nil
	}

	ext := filepath.Ext(m.Filename)
	if ext != ".mp4" && ext != ".avi" {
		return &types.Response{
			Message: "仅支持MP4/AVI格式，请重新选择",
			Code:    500,
			Data:    nil,
		}, nil
	}

	upload, err := pkg.Upload(video, m)
	if err != nil {
		return &types.Response{
			Message: "文件上传失败",
			Code:    500,
			Data:    nil,
		}, nil
	}

	data, err := l.svcCtx.VideoRpc.UploadVideo(l.ctx, &videorpc.UploadVideoRequest{
		UserId:        req.UserId,
		VideoTitle:    req.VideoTitle,
		VideoCategory: req.VideoCategory,
		VideoLink:     upload,
		CoverLink:     upload,
		VideoIntro:    req.VideoIntro,
		TopicId:       req.TopicId,
		VideoStatus:   req.VideoStatus,
	})
	if err != nil {
		return &types.Response{
			Message: err.Error(),
			Code:    500,
			Data:    nil,
		}, nil
	}
	return &types.Response{
		Message: "视频上传成功",
		Code:    200,
		Data:    data,
	}, nil

}
